package com.irwin.skin;


import android.os.Bundle;
import android.support.annotation.IdRes;
import android.support.annotation.LayoutRes;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.irwin.skin.ISkinnable;
import com.irwin.skin.SkinManager;
import com.irwin.skin.SkinUtils;
import com.irwin.skin.resources.BaseResources;

public class BaseFragment extends Fragment implements ISkinnable {

    private ViewGroup mContentContainer;
    private View mContentView;
    private boolean mForceUpdateSkin = false;


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        registerSkinCallback();
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mContentContainer = (ViewGroup) inflater.inflate(R.layout.frag_skin_container, container, false);
        setContentView(getLayoutRes());
        onViewCreated(mContentView);
        return mContentContainer;
    }

    public View findViewById(@IdRes int id) {
        if (mContentView != null) {
            return mContentView.findViewById(id);
        }
        return null;
    }

    protected void onViewCreated(View view) {
        bindViewData();
    }

    public void setContentView(@LayoutRes int resId) {
        View v = getSkinResources().getView(mContentContainer.getContext(), resId);
        setContentView(v);
    }

    protected void registerSkinCallback() {
        SkinManager.getInstance().register(this);
    }

    protected void unregisterSkinCallback() {
        SkinManager.getInstance().unregister(this);
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        unregisterSkinCallback();
    }

    @Override
    public void bindViewData() {

    }

    @Override
    public int getLayoutRes() {
        return 0;
    }

    @Override
    public void onSkinChanged(BaseResources resources) {
        final View v = resources.getView(mContentContainer.getContext(), getLayoutRes());
        if (!isForceUpdateSkin() && SkinUtils.isSameLayout(mContentView, v)) {
            return;
        }
        setContentView(v);
        bindViewData();
    }


    public void setContentView(View v) {
        if (mContentContainer != null) {
            mContentContainer.removeAllViews();
            mContentContainer.addView(v);
            mContentView = v;
        }
    }


    public BaseResources getSkinResources() {
        return SkinManager.getInstance().getResources();
    }

    protected boolean isForceUpdateSkin() {
        return mForceUpdateSkin;
    }


    protected void setForceUpdateSkin(boolean force) {
        mForceUpdateSkin = force;
    }
}

